import React, { useState, useMemo, useEffect, useImperativeHandle, forwardRef } from "react";
import {
    Collapse,
    NavBar,
    List,
    Empty,
    Skeleton,
    DatePicker,
    Button,
    TextArea,
    Popup,
} from "antd-mobile";
import {
    findCustomInfo,
    findHistoryProcess,
    findCurrentProcess,
    findPreviewProcess,
    chk,
} from "src/api/pqsstartWkInfo";
import { UserOutline, CalendarOutline } from "antd-mobile-icons";
import * as dayjs from "dayjs";
import "./index.scss";
import Toast from "src/pages/components/clickableToast";
import PropTypes from "prop-types";

const SignTable = forwardRef((props, ref) => {
    const [_stepInfo, set_stepInfo] = useState({
        activeNode: 1,
        nodeList: [],
    });
    const [curNodeArr, setCurNodeArr] = useState([]);
    const [signStepLoading, setSignStepLoading] = useState(false);
    const [nextUserIds, setNextUserIds] = useState("");

    const [reson, setReason] = useState("");
    const [userSignDate, setUserSignDate] = useState(dayjs().format("YYYY-MM-DD HH:mm:ss"));
    const [dateVisible, setDateVisible] = useState(false);

    const [show, setShow] = useState(false);

    const { addUserId, kid, userId, optionOne, commitSignCallBack } = props;

    // 工作流数据

    useImperativeHandle(ref, () => ({
        setShow,
    }));

    const getWorkflowKid = () => {
        if (!kid) return;
        findCustomInfo(kid).then(res => {
            if (res.success) {
                getCurrentNodeId(kid).then(result => {
                    setCurNodeArr(result);
                    getWorkflowNode(res.data[0].processDefinitionKey, result);
                });
            }
        });
    };

    const getCurrentNodeId = kid => {
        return new Promise(resolve => {
            findCurrentProcess(kid).then(res => {
                if (res.success) {
                    let curNodelist = [];
                    let reslist = res.data[0].nodeList;
                    for (let i = 0; i < reslist.length; i++) {
                        const ele = reslist[i];
                        //   that.handleBtnPassName(ele) // 处理按钮显示文字
                        curNodelist.push({
                            nodeId: ele.nodeId,
                            nodeName: ele.nodeName,
                            data: ele.assigneeList,
                        }); // 当前审核节点的所有信息
                    }
                    resolve(curNodelist);
                }
            });
        });
    };

    // 获取当前之后的流程
    const getWorkflowNode = (key, curr) => {
        //提交数据的kid
        let businesskey = kid;
        setSignStepLoading(true);
        findPreviewProcess(
            addUserId || userId, // 提交审核人Id
            key, // 前一个步骤的 processDefinitionKey
            curr[curr.length - 1].nodeId, // 最后一个步骤的nodeId
            businesskey,
        )
            .then(res => {
                if (res.success) {
                    let nextlist = res.data.map(e => ({
                        nodeId: e.nodeId,
                        nodeName: e.nodeName,
                        data: e.assigneeList,
                    }));
                    let stepInfo = {
                        activeNode: 1,
                        nodeList: [],
                    };
                    // 拼接步骤
                    let arrlist = curr.concat(nextlist); // curr当前步骤，nextlist当前步骤之后的步骤
                    // 获取下个步骤的人员id，为之后工作准备
                    getNextStepKids(nextlist);
                    stepInfo.nodeList = [{ nodeId: "0", nodeName: "流程开始", data: [] }];
                    // 处理出现退回上一步的时候重复的节点，只取走后一个
                    stepInfo.nodeList = stepInfo.nodeList.concat(arrlist).reverse();
                    // 去重
                    stepInfo.nodeList = [
                        ...new Set(
                            stepInfo.nodeList.map(e => {
                                return e.nodeId;
                            }),
                        ),
                    ].map(e => {
                        return stepInfo.nodeList.find(a => {
                            return e == a.nodeId;
                        });
                    });

                    stepInfo.nodeList = stepInfo.nodeList.reverse();
                    stepInfo.nodeList.push({ nodeId: "100", nodeName: "流程结束", data: [] });
                    // 当前选中的步骤高亮
                    stepInfo.activeNode = stepInfo.nodeList
                        .map(e => e.nodeId)
                        .indexOf(curr[curr.length - 1].nodeId);
                    set_stepInfo(stepInfo);
                }
            })
            .then(_ => {
                setSignStepLoading(false);
            });
    };

    const getNextStepKids = nextlist => {
        if (nextlist && nextlist.length > 0) {
            let firstUser = nextlist[0].data;
            let _nextUserIds = "";
            firstUser.map(user => {
                _nextUserIds += user.userId + ",";
            });
            setNextUserIds(_nextUserIds);
        }
    };

    const saveBeforeVerify = () => {
        if (!reson || reson.trim() === "") {
            Toast.show({
                content: "请填写审核意见！",
            });
            return false;
        }
        return true;
    };

    const handleCommitPass = () => {
        if (!saveBeforeVerify()) {
            return false;
        }
        const params = {
            chkFlag: "agree", //审核标志（agree:同意；disAgree:不同）
            nextUserIds: nextUserIds ? nextUserIds.substring(0, nextUserIds.length - 1) : null, // //已在提交时通知所有审核人员
        };
        handleAudit(params, { msg: `${"通过"}操作成功！` });
    };

    const handleAudit = (params, info) => {
        let paramsData = {
            assignee: userId, //审核人Id
            businesskey: kid, //选中业务kid
            reson, //审核意见
            userSignDate, //签名日期
            sessionId: "", // 预签签名拿回来的序列
            nodeId: curNodeArr[curNodeArr.length - 1].nodeId, //节点ID
            formType: optionOne && optionOne.formType, // 选填参数，配置表的下拉选择的类型formType 在开工报告，方案管理中使用
            workflowModule: optionOne && optionOne.workflowModule,
        };
        paramsData = Object.assign({}, paramsData, params);
        Toast.show({
            icon: "loading",
            content: "提交审核中",
            duration: 0,
        });

        chk(paramsData)
            .then(res => {
                Toast.show({
                    icon: "success",
                    content: info.msg || "操作成功",
                });
                setShow(false);
                commitSignCallBack && commitSignCallBack(paramsData.chkFlag);
            })
            .finally(_ => {});
    };

    const handleCommitBack = () => {
        if (!saveBeforeVerify()) {
            return false;
        }
        let params = {
            chkFlag: "disAgree", //审核标志（agree:同意；disAgree:不同）
        };
        handleAudit(params, { msg: `退回操作成功！` });
    };

    const handleCommitBackOneStep = () => {
        let params = {
            chkFlag: "disAgree", //审核标志（agree:同意；disAgree:不同）
            rollbackStepCount: 1, //退回上一步，多加一个参数
        };
        handleAudit(params, { msg: `${"退回上一步"}操作成功！` });
    };

    useEffect(() => {
        show && getWorkflowKid();
    }, [show]);

    const totalSteps = _stepInfo.nodeList.length;
    const current = _stepInfo.activeNode || 1;

    return (
        <Popup
            visible={show}
            onMaskClick={() => setShow(false)}
            onClose={() => setShow(false)}
            bodyStyle={{ height: "78vh" }}
            showCloseButton
            className="sign-page"
            closeOnMaskClick
        >
            <div className="sign-page">
                <h2>审核详情</h2>
                <div className="sign-content">
                    <Collapse defaultActiveKey={["1", "2", "3"]}>
                        <Collapse.Panel key="1" title="审核流程">
                            <List mode="card">
                                {signStepLoading ? (
                                    <Skeleton.Paragraph lineCount={5} animated />
                                ) : !_stepInfo.nodeList?.length ? (
                                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                                ) : (
                                    <div className="m-steps-box">
                                        {_stepInfo.nodeList.map((node, idxn) => {
                                            const steps = node.data.map((des, s) => {
                                                const isSign = current === idxn;
                                                return (
                                                    <li key={s} className="u-steps-li">
                                                        <UserOutline />
                                                        <span> </span>
                                                        <span>{des.userName}</span>
                                                        {des.endTime &&
                                                            des.operateType === "AGREE" && (
                                                                <span>
                                                                    {" "}
                                                                    ({des.endTime.slice(
                                                                        0,
                                                                        10,
                                                                    )}){" "}
                                                                </span>
                                                            )}
                                                        {des.reason && (
                                                            <span className="status">
                                                                {des.reason}
                                                            </span>
                                                        )}
                                                    </li>
                                                );
                                            });

                                            const finished = current > idxn ? " finished" : "";
                                            const first =
                                                idxn === 0 && idxn !== totalSteps ? " first" : "";
                                            const process =
                                                current === idxn && idxn !== totalSteps
                                                    ? " process"
                                                    : "";
                                            const lastProcess =
                                                current === totalSteps && idxn + 1 === totalSteps
                                                    ? " last-process"
                                                    : "";
                                            const middleWait =
                                                current < idxn && idxn + 1 !== totalSteps
                                                    ? " middle-wait"
                                                    : "";
                                            const lastWait =
                                                current < idxn && idxn + 1 === totalSteps
                                                    ? " last-wait"
                                                    : "";
                                            const last = idxn + 1 === totalSteps ? " last" : "";
                                            return (
                                                <div
                                                    key={idxn}
                                                    className={`m-steps-item ${finished}${first}${process}${lastProcess}${middleWait}${lastWait}${last}`}
                                                >
                                                    <div className="m-info-wrap">
                                                        <div className="m-steps-icon">
                                                            {current <= idxn ? (
                                                                <span className="u-icon">
                                                                    {idxn}
                                                                </span>
                                                            ) : (
                                                                <svg
                                                                    className="u-icon"
                                                                    viewBox="64 64 896 896"
                                                                    data-icon="check"
                                                                    aria-hidden="true"
                                                                    focusable="false"
                                                                >
                                                                    <path d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 0 0-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"></path>
                                                                </svg>
                                                            )}
                                                        </div>
                                                        <div className="m-steps-content">
                                                            <div className="u-steps-title">
                                                                {node.nodeName}
                                                                {current === idxn && (
                                                                    <span className="signing">
                                                                        审核中
                                                                    </span>
                                                                )}
                                                            </div>
                                                            <div
                                                                className={`u-steps-description ${
                                                                    node.data.length >= 10
                                                                        ? "u-long"
                                                                        : ""
                                                                }`}
                                                            >
                                                                {steps}
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                )}
                            </List>
                        </Collapse.Panel>
                        <Collapse.Panel key="2" title="审核意见">
                            <div className="collapse-mind">
                                <TextArea
                                    placeholder="请输入审核意见"
                                    value={reson}
                                    onChange={val => {
                                        setReason(val);
                                    }}
                                    rows={4}
                                />
                            </div>
                        </Collapse.Panel>
                        <Collapse.Panel key="3" title="签名日期">
                            <div className="collapse-sign">
                                <div
                                    className="date"
                                    onClick={() => {
                                        setDateVisible(true);
                                    }}
                                >
                                    <span>{userSignDate?.substring(0, 10)}</span>
                                    <CalendarOutline />
                                </div>
                                <div className="operate">
                                    {/* <Button
                                        block
                                        size="large"
                                        onClick={handleCommitBackOneStep}
                                    >
                                        退回上一步
                                    </Button> */}
                                    <Button block size="large" onClick={handleCommitBack}>
                                        退回
                                    </Button>
                                    <Button
                                        block
                                        size="large"
                                        color="primary"
                                        onClick={handleCommitPass}
                                    >
                                        通过
                                    </Button>
                                </div>
                            </div>
                        </Collapse.Panel>
                    </Collapse>
                </div>
                <DatePicker
                    title="时间选择"
                    visible={dateVisible}
                    onClose={() => {
                        setDateVisible(false);
                    }}
                    onConfirm={val => {
                        setUserSignDate(dayjs(val).format("YYYY-MM-DD HH:mm:ss"));
                    }}
                />
            </div>
        </Popup>
    );
});

SignTable.propTypes = {
    userId: PropTypes.number,
    addUserId: PropTypes.number,
    kid: PropTypes.string,
    optionOne: PropTypes.object,
    commitSignCallBack: PropTypes.func,
};

export default SignTable;
